import * as YvanUI from "yvan-ui-wotu"
import CustomData, {dataRaw} from "../widget/custom.data"
import CustomDict from '../widget/custom.dict'
import {SimpleImportView} from "../widget/SimpleImportView";

const React = YvanUI.React
const _ = YvanUI.lodash
const XLSX = YvanUI.XLSX

interface Ref {
    gridAll: YvanUI.Grid
    gridOk: YvanUI.Grid
    gridError: YvanUI.Grid
    gridErrMsg: YvanUI.Grid
}

export default class ExcelImport extends YvanUI.Scope<void, Ref> {

    main = this.$$({
        check1: ''
    })

    onRender() {
        //
        // this.watch(()=>this.main.check1,
        //     (v)=> {
        //         this.refs.grid1.loading = (v === '1')
        //     });
    }

    importResult = {
        allData: [],
        okData: [],
        errorData: [],
        errorMsgData: [],
    }

    markCellError(sender, params) {
        for (let i = 0; i < this.importResult.errorMsgData.length; i++) {
            const v = this.importResult.errorMsgData[i];
            if (v.importID === params.data.__importID__ && params.field === v.field) {
                return {backgroundColor: 'red'};
            }
        }
    }
    markRowErrorToCell(sender, params) {
        for (let i = 0; i < this.importResult.errorMsgData.length; i++) {
            const v = this.importResult.errorMsgData[i];
            if (v.importID === params.data.__importID__) {
                return {backgroundColor: '#ff4d4f'};
            }
        }
    }
    onCellClicked(sender, params) {
        if (params.field === "__importID__") {
            this.refs.gridErrMsg?.selectRow(params.data.__importID__ + "");
        } else {
            this.refs.gridErrMsg?.selectRow(params.data.__importID__ + "_" + params.field)
        }

    }

    vjson = {
        view: 'page',
        title: '表格格式化',
        items: [
            {
                view:'card',
                size: 'small',
                className:'form-item-no-bottom',
                items:[
                    {
                        view: "row",
                        items: [
                            {
                                view: "col",
                                span: 6,
                                items: [
                                    {
                                        view: 'button',
                                        text: "下载模版",
                                        onClick: ()=>{
                                            const filename = "客户列表.xlsx"; //文件名称
                                            var ws_name = "Sheet1"; //Excel第一个sheet的名称
                                            var wb = XLSX.utils.book_new(), ws = XLSX.utils.aoa_to_sheet([['客户编号','客户名称','助记码','客户类型','客户类别','创建时间','更新时间']]);
                                            XLSX.utils.book_append_sheet(wb, ws, ws_name);  //将数据添加到工作薄
                                            XLSX.writeFile(wb, filename); //导出Excel
                                        }
                                    }
                                ]
                            },
                            {
                                view: "col",
                                span: 6,
                                items: [
                                    {
                                        view: 'excelImport',
                                        fields: [
                                            {field: "customercode"},
                                            {field: "customername", validate: ({field, ov, nv, rowIndex, data, rowDatas})=>{
                                                    if (ov === '西安 杨小卫') {
                                                        return field.title + ":" + "这个人不行"
                                                    }
                                                    return true}},
                                            {field: "logogram"},
                                            {field: "industryclass", data: CustomDict.industryclass},
                                            {
                                                field: "customertype",
                                                data: this.$get(
                                                    () => new Promise((resolve, reject) => {
                                                        setTimeout(() => resolve(CustomDict.customertype), 1000)
                                                    })
                                                )
                                            },
                                            {field: "create_at", validate: ({field, ov, nv, rowIndex, data, rowDatas})=>{return true}},
                                            {field: "update_at", validate: ({field, ov, nv, rowIndex, data, rowDatas})=>{return true}},
                                        ],
                                        rowValidate: (sender: any, {fields, data, rowIndex, rowDatas})=>{
                                            if (rowIndex%3 === 0) {
                                                return "校验错误"
                                            }
                                            return true
                                        },
                                        dataStartRow: 2,
                                        onChange: (sender: any,result)=> {
                                            debugger
                                            this.importResult = result
                                            this.refs.gridAll?.refresh();
                                            this.refs.gridOk?.refresh();
                                            this.refs.gridError?.refresh();
                                            this.refs.gridErrMsg?.refresh();
                                        }
                                    },
                                ]
                            }
                        ]
                    },
                ]
            },
            {
                view: 'spliter',
                split: 'vertical',
                defaultSize: '50%',
                minSize: '10px',
                maxSize: '1200px',
                items: [
                    {
                        view: 'card',
                        size: 'small',
                        items:[
                            {
                                view: 'tabs',
                                defaultTabIndex: 0,
                                items: [
                                    {
                                        title: '所有数据',
                                        content: {
                                            view: 'grid',
                                            title: '表格格式化',
                                            ref: 'gridAll',
                                            idField: "__importID__",
                                            exportExcelName: "表格导出.xlsx",
                                            columns: [
                                                {
                                                    field: "__importID__",
                                                    title: "行号",
                                                    width: 80,
                                                    onStyle: "markRowErrorToCell",
                                                    onCellClicked: 'onCellClicked'
                                                },
                                                {field: "customerid", hidden: true},
                                                {
                                                    field: "customercode",
                                                    title: "客户编号",
                                                    width: 80,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "customername",
                                                    title: "客户名称",
                                                    width: 120,
                                                    onStyle: "markCellError",
                                                    onCellClicked: 'onCellClicked'
                                                },
                                                {field: "logogram", title: "助记码", width: 80, onStyle: "markCellError"},
                                                {
                                                    field: "industryclass",
                                                    title: "客户类型",
                                                    width: 100,
                                                    data: CustomDict.industryclass,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "customertype",
                                                    title: "客户类别",
                                                    width: 100,
                                                    data: CustomDict.customertype,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "create_at",
                                                    title: '创建时间',
                                                    width: 120,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "update_at",
                                                    title: '更新时间',
                                                    width: 120,
                                                    onStyle: "markCellError"
                                                }
                                            ],
                                            autoDataSource: true,
                                            // getRowClass: (params)=>{
                                            //     if (params.data.__hasError__) {
                                            //         return 'ag-row-error-low'
                                            //     }
                                            // },
                                            dataSource: {
                                                func: () => this.importResult.allData
                                            },
                                            onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any[], raw: any, api: any, isExportData: boolean) => {
                                                if (isExportData === true) {
                                                    return dataOrgin
                                                }
                                                const offset = (sender.currentPage - 1) * sender.pageSize
                                                const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                                                return {
                                                    pagination: {
                                                        current: sender.currentPage,
                                                        total: dataOrgin.length,
                                                        size: sender.pageSize
                                                    },
                                                    data: dataOrgin.slice(offset, endOffset)
                                                }
                                            }
                                        }
                                    },
                                    {
                                        title: '正确的数据',
                                        content: {
                                            view: 'grid',
                                            title: '表格格式化',
                                            ref: 'gridOk',
                                            idField: "__importID__",
                                            exportExcelName: "正确的数据.xlsx",
                                            columns: [
                                                {field: "__importID__", title: "行号", width: 80},
                                                {field: "customerid", hidden: true},
                                                {field: "customercode", title: "客户编号", width: 80,},
                                                {field: "customername", title: "客户名称", width: 120},
                                                {field: "logogram", title: "助记码", width: 80},
                                                {
                                                    field: "industryclass",
                                                    title: "客户类型",
                                                    width: 100,
                                                    data: CustomDict.industryclass
                                                },
                                                {
                                                    field: "customertype", title: "客户类别", width: 100,
                                                    data: this.$get(
                                                        () => new Promise((resolve, reject) => {
                                                            resolve(CustomDict.customertype)
                                                        })
                                                    )
                                                },
                                                {field: "create_at", title: '创建时间', width: 120, formatter: 'fmtDate'},
                                                {
                                                    field: "update_at",
                                                    title: '更新时间',
                                                    width: 120,
                                                    formatter: 'fmtDateNoTime'
                                                }
                                            ],
                                            autoDataSource: true,
                                            dataSource: {
                                                func: () => this.importResult.okData
                                            },
                                            onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any[], raw: any, api: any, isExportData: boolean) => {
                                                if (isExportData === true) {
                                                    return dataOrgin
                                                }
                                                const offset = (sender.currentPage - 1) * sender.pageSize
                                                const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                                                return {
                                                    pagination: {
                                                        current: sender.currentPage,
                                                        total: dataOrgin.length,
                                                        size: sender.pageSize
                                                    },
                                                    data: dataOrgin.slice(offset, endOffset)
                                                }
                                            }
                                        }
                                    },
                                    {
                                        title: '错误的数据',
                                        content: {
                                            view: 'grid',
                                            title: '表格格式化',
                                            ref: 'gridError',
                                            idField: "__importID__",
                                            exportExcelName: "错误的数据.xlsx",
                                            columns: [
                                                {
                                                    field: "__importID__",
                                                    title: "行号",
                                                    width: 80,
                                                    onStyle: "markRowErrorToCell"
                                                },
                                                {field: "customerid", hidden: true},
                                                {
                                                    field: "customercode",
                                                    title: "客户编号",
                                                    width: 80,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "customername",
                                                    title: "客户名称",
                                                    width: 120,
                                                    onStyle: "markCellError"
                                                },
                                                {field: "logogram", title: "助记码", width: 80, onStyle: "markCellError"},
                                                {
                                                    field: "industryclass",
                                                    title: "客户类型",
                                                    width: 100,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "customertype",
                                                    title: "客户类别",
                                                    width: 100,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "create_at",
                                                    title: '创建时间',
                                                    width: 120,
                                                    onStyle: "markCellError"
                                                },
                                                {
                                                    field: "update_at",
                                                    title: '更新时间',
                                                    width: 120,
                                                    onStyle: "markCellError"
                                                }
                                            ],
                                            // getRowStyle: (params)=>{
                                            //     if (params.data.__hasError__) {
                                            //         return {background: 'rgba(254,10,10,0.24)'}
                                            //     }
                                            // },
                                            autoDataSource: true,
                                            dataSource: {
                                                func: () => this.importResult.errorData
                                            },
                                            onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any[], raw: any, api: any, isExportData: boolean) => {
                                                if (isExportData === true) {
                                                    return dataOrgin
                                                }
                                                const offset = (sender.currentPage - 1) * sender.pageSize
                                                const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                                                return {
                                                    pagination: {
                                                        current: sender.currentPage,
                                                        total: dataOrgin.length,
                                                        size: sender.pageSize
                                                    },
                                                    data: dataOrgin.slice(offset, endOffset)
                                                }
                                            }
                                        }
                                    }
                                ]
                            }
                        ]
                    },
                    {
                        view: 'card',
                        size: 'small',
                        items: [{
                            view: 'grid',
                            title: '表格格式化',
                            ref: 'gridErrMsg',
                            idField: "errorId",
                            exportExcelName: "错误明细.xlsx",
                            columns: [
                                {field: "errorId", title: "ID", hidden: true},
                                {field: "importID", title: "行号", width: 80},
                                {field: "field", title: "字段", width: 120},
                                {field: "value", title: "值", width: 120},
                                {field: "errormessage", title: "错误信息", width: 200},
                            ],
                            // getRowStyle: (params)=>{
                            //     return {background: 'red'}
                            // },
                            autoDataSource: true,
                            dataSource: {
                                func: ()=> this.importResult.errorMsgData
                            },
                            onDataSourceAfter: (sender: YvanUI.Grid, dataOrgin: any[], raw: any, api: any, isExportData: boolean) => {
                                if (isExportData === true) {
                                    return dataOrgin
                                }
                                const offset = (sender.currentPage - 1) * sender.pageSize
                                const endOffset = (offset + sender.pageSize > dataOrgin.length) ? dataOrgin.length : offset + sender.pageSize
                                return {
                                    pagination: {
                                        current: sender.currentPage,
                                        total: dataOrgin.length,
                                        size: sender.pageSize
                                    },
                                    data: dataOrgin.slice(offset, endOffset)
                                }
                            },
                            onRowSelect: (sender: YvanUI.Grid, data)=>{
                                this.refs.gridAll?.selectRow(data.importID)
                                this.refs.gridOk?.selectRow(data.importID)
                                this.refs.gridError?.selectRow(data.importID)
                            }
                        }]
                    }
                ]
            },
        ]
    }
}